package com.mbbmap.map;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.classes.Casemast;
import com.classes.CasemastFactory;
import com.mbbmap.app.home.SecUsersHome;
import com.mbbmap.app.manager.ConfigManager;
import com.mbbmap.security.action.CommonDispatchAction;
import com.mbbmap.security.dao.SecAccessDao;
import com.mbbmap.security.dao.SecGroupsDao;
import com.mbbmap.security.dao.SecUserDao;
import com.mbbmap.util.Constants;
import com.mbbmap.util.EncryptionHelper;

public class TypeAppAction extends CommonDispatchAction {
private int iApp7 = 0; //APP007
	
	private boolean authorized(HttpServletRequest request){
		HttpSession session = request.getSession(false);
		@SuppressWarnings("unchecked")
		ArrayList<SecAccessDao> secGroupAccessList = (ArrayList<SecAccessDao>) session.getAttribute(Constants.LOGON_ACCESS_LIST);
		
		this.iApp7 = 0;
		
		for(int i=0;i<secGroupAccessList.size();i++){
			SecAccessDao secaccessDao = (SecAccessDao)secGroupAccessList.get(i);
			String strModuleCode  = secaccessDao.getModuleCode();
			if(strModuleCode.equals("APP007")){
				this.iApp7 = 1;
			}
		}
		
		if(this.iApp7 > 0) {
			return true;
		}
		
		return false;
	}
	
	public ActionForward init(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

			final String PROG_ID="TypeAppAction.init";

			System.out.println(PROG_ID + " : BEGIN");
			HttpSession session = request.getSession(false);
			
			String nextPage = null;
			
			//check session condition
			if (session == null){
				return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
			}
//			if(!isTokenValid(request)){
//				System.out.println("Token validation failed!");
//				session.invalidate();
//				return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
//			}else{
//				resetToken(request);
//				System.out.println("Token validation passed!");
//			}
			
			// browser javasript is not enable
			if (request.getParameter(Constants.PARAM_JS_ENABLE) != null && request.getParameter(Constants.PARAM_JS_ENABLE).equals("no") ) {
				String actionMsg = ConfigManager.getInstance().get(Constants.MSG_ERROR_JAVASCRIPT_NOT_ENABLE);
				session.setAttribute(Constants.LOGON_ERR_MSG, actionMsg);
				if (DEBUG) System.out.println("... Javascript not enable");
				return mapping.findForward(Constants.KEY_ACTION_MAPPING_NOSCRIPT);
			}
			String sessionstatus = (String) session.getAttribute(Constants.VISIT_STATUS);
			SecUserDao oSecUserDao = (SecUserDao) session.getAttribute(Constants.LOGGED_USER);// read user session time
			
			String strFwd = "";
			if (oSecUserDao == null){
				strFwd ="sessionError";
			}
			else
			{
				
			}
			if (sessionstatus != null){
				if (DEBUG) System.out.println("sessionstatus !=null");
				if ((sessionstatus.equals(Constants.VISIT_STATUS_VISITED)) || (session.isNew())){
					//This is from refresh button.. set session expires.
					if (DEBUG) System.out.println("sessionstatus !=null 2");
					String errMsg = ConfigManager.getInstance().get(Constants.MSG_LOGON_ERR_LOGOUT_ACTIVE_SESSION);
					session.setAttribute(Constants.LOGON_ERR_MSG, errMsg);
					return mapping.findForward(Constants.KEY_ACTION_LOGOUT);

				}
			}
			else if (oSecUserDao == null){// if the session expire, it will bring user to timeout screen
				
				return mapping.findForward(strFwd);
		
			}
			
			
			/********************************************************************************/
			/* Custom code starts here */
			
			Date d = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			request.setAttribute("todayDate", df.format(d));
			
			ArrayList<SecGroupsDao> groupList = this.myGroupList(request);
			request.setAttribute("groupList", groupList);
			
			String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
			
			nextPage = "application_submission";
			
			if(this.authorized(request) == false){
				nextPage="not_authorized";
			}
			
			ArrayList<String> statusList = CasemastFactory.getStatusFilter(4,0);
			if(statusList == null){
				json_error(CasemastFactory.getMessage(), response);
				return null;
			}
			
			request.setAttribute("statusList", statusList);
			
			TreeMap<String, String> search = new TreeMap<String, String>();
			
			if(request.getParameter("search_submit") != null){
				if(request.getParameter("status") != null){
					search.put("status", sanitizePwd(request.getParameter("status")));
				}
				
				if(request.getParameter("case_id") != null){
					search.put("case_id", sanitize(request.getParameter("case_id")));
				}
				
				if(request.getParameter("merchant_name") != null){
					search.put("merchant_name", sanitize(request.getParameter("merchant_name")));
				}
				
				if(request.getParameter("submit_date") != null){
					String paramStr = request.getParameter("submit_date");
					if(paramStr.matches("^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$")) {
						search.put("submit_date", sanitize(request.getParameter("submit_date")));
					} else if(paramStr.isEmpty() == false) {
						search.put("submit_date", (String) request.getAttribute("todayDate"));
					}
				}
				
				if(request.getParameter("group_code") != null){
					search.put("group_code", EncryptionHelper.decrypt(request.getParameter("group_code")));
				}
				
				if(request.getParameter("group_user") != null){
					search.put("group_user", EncryptionHelper.decrypt(request.getParameter("group_user")));
				}
				
				if(request.getParameter("reseller_location") != null){
					search.put("reseller_location", sanitize(request.getParameter("reseller_location")));
				}
				
				if(request.getParameter("application_type") != null){
					search.put("application_type", request.getParameter("application_type"));
				}
			}
			else {
				search.put("submit_date", (String) request.getAttribute("todayDate"));
			}
			
			ArrayList<Casemast> cArr = CasemastFactory.getCasemasts(oSecUserDao.getGroupCode(), search);
			if(cArr == null){
				json_error(CasemastFactory.getMessage(), response);
				return null;
			}
			
			
			request.setAttribute("search", search);
			request.setAttribute("cArr", cArr);
			
			ArrayList<SecUserDao> userList = new ArrayList<SecUserDao>();
			if ((strEMerchant != null) && (!strEMerchant.equals(""))){
				if(search.containsKey("group_code") && search.get("group_code").length() > 0){
					userList = SecUsersHome.getInstance().findSecGroupUserList(strEMerchant, search.get("group_code"));
				}
			}
			
			request.setAttribute("userList", userList);
			
			
			return mapping.findForward(nextPage);
		}
}
